<script setup lang="ts">
import type { FormInst, FormRules } from 'naive-ui'
import { addDevice, updateDevice } from '@/service'

interface Props {
  visible: boolean
  type: 'add' | 'edit'
  modalData?: Api.Device.Info | null
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  type: 'add',
  modalData: null,
})

const emit = defineEmits<Emits>()

const showModal = computed({
  get() {
    return props.visible
  },
  set(val) {
    emit('update:visible', val)
  },
})

const title = computed(() => {
  return props.type === 'add' ? '新建设备' : '编辑设备'
})

const loading = ref(false)
const formRef = ref<FormInst | null>(null)

const formData = ref<Api.Device.AddRequest>({
  name: '',
  type: {
    name: '',
    driver: '',
    properties: [],
  },
  address: '',
  collector: {},
  alone: false,
  serial: {},
  initialVal: 0,
  scale: 1,
})

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
  ],
  address: [
    { required: true, message: '请输入通讯地址', trigger: 'blur' },
  ],
  'type.name': [
    { required: true, message: '请输入设备类型名称', trigger: 'blur' },
  ],
}

// 监听visible和modalData变化，初始化表单数据
watch(
  [() => props.visible, () => props.modalData, () => props.type],
  ([visible, data, type]) => {
    if (visible && data && type === 'edit') {
      formData.value = {
        name: data.name,
        type: data.type || { name: '', driver: '', properties: [] },
        address: data.address,
        collector: data.collector || {},
        alone: Boolean(data.alone),
        serial: data.serial || {},
        initialVal: data.initialVal || 0,
        scale: data.scale || 1,
      }
    }
    else if (visible && type === 'add') {
      resetForm()
    }
  },
  { immediate: true },
)

function resetForm() {
  formData.value = {
    name: '',
    type: {
      name: '',
      driver: '',
      properties: [],
    },
    address: '',
    collector: {},
    alone: false,
    serial: {},
    initialVal: 0,
    scale: 1,
  }
}

function handleClose() {
  showModal.value = false
  resetForm()
}

async function handleConfirm() {
  try {
    await formRef.value?.validate()
    loading.value = true

    const apiCall = props.type === 'add' ? addDevice : updateDevice
    const { isSuccess, message } = await apiCall(formData.value)

    if (isSuccess) {
      window.$message.success(props.type === 'add' ? '添加成功' : '更新成功')
      emit('success')
      handleClose()
    }
    else {
      window.$message.error(message || '操作失败')
    }
  }
  catch (e: any) {
    if (e?.message) {
      window.$message.error(e.message)
    }
  }
  finally {
    loading.value = false
  }
}
</script>

<template>
  <n-modal
    v-model:show="showModal"
    :title="title"
    preset="card"
    :style="{ width: '600px' }"
    :segmented="{ content: true }"
  >
    <n-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-placement="left"
      label-width="100"
    >
      <n-form-item label="设备名称" path="name">
        <n-input
          v-model:value="formData.name"
          placeholder="请输入设备名称"
          :disabled="type === 'edit'"
        />
      </n-form-item>

      <n-form-item label="设备类型" path="type.name">
        <n-input
          v-model:value="formData.type.name"
          placeholder="请输入设备类型名称"
        />
      </n-form-item>

      <n-form-item label="驱动程序" path="type.driver">
        <n-input
          v-model:value="formData.type.driver"
          placeholder="请输入驱动程序路径"
        />
      </n-form-item>

      <n-form-item label="通讯地址" path="address">
        <n-input
          v-model:value="formData.address"
          placeholder="请输入通讯地址"
        />
      </n-form-item>

      <n-form-item label="初始值" path="initialVal">
        <n-input-number
          v-model:value="formData.initialVal"
          placeholder="请输入初始值"
          class="w-full"
        />
      </n-form-item>

      <n-form-item label="倍率" path="scale">
        <n-input-number
          v-model:value="formData.scale"
          placeholder="请输入倍率"
          :min="0"
          class="w-full"
        />
      </n-form-item>

      <n-form-item label="独立开关" path="alone">
        <n-switch v-model:value="formData.alone" />
      </n-form-item>
    </n-form>

    <template #footer>
      <n-space justify="end">
        <n-button @click="handleClose">
          取消
        </n-button>
        <n-button type="primary" :loading="loading" @click="handleConfirm">
          确定
        </n-button>
      </n-space>
    </template>
  </n-modal>
</template>

